package com.zysd.collection.scheduler.service.record;

import com.lensyn.common.exception.entity.MsgException;
import com.lensyn.common.utils.domain.common.PageResponse;
import com.lensyn.common.utils.system.response.Response;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.zysd.collection.scheduler.domain.meter.MeterInfoDto;
import com.zysd.collection.scheduler.entity.Terminal;
import com.zysd.collection.scheduler.system.constants.Constants;
import com.zysd.collection.scheduler.system.util.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 售电采集 接口封装
 *
 * @author liuht
 * @date 2017/11/10 17:25
 */
@SuppressWarnings("unchecked")
@Service
@DefaultProperties(groupKey = "ZYSD-COLLECTION-SCHEDULER-RECORD")
public class RecordApiService extends AbstractRecordApiService {

    /**
     * 查询售电系统终端list
     *
     * @param params 查询参数
     *               ① 什么都不传 查询所有
     *               ② companyId 售电公司ID
     *               ③ customerId 客户ID
     * @return Response
     */
    @HystrixCommand(fallbackMethod = "fastFallbackWithMap")
    public Response getCusTerminal(Map<String, Object> params) {
        String url = recordUrl + "terminals";
        url = setGetParam(url, params);
        return restTemplate.getForObject(url, Response.class);
    }

    /**
     * 返回所有终端
     */
    @HystrixCommand(fallbackMethod = "fastFallbackListTerminal")
    public List<Terminal> getAllTerminals() {
        String url = recordUrl + "terminals";
        Response response = restTemplate.getForObject(url, Response.class);
        if (response.getMeta().getCode() == Constants.RESPONSE_CODE_YES
                && response.getData() != null) {
            List<Map> ters = (List<Map>) response.getData();
            List<Terminal> terminals = new ArrayList<>(ters.size());
            ters.forEach(map -> terminals.add(BeanUtils.mapToBean(map, Terminal.class)));
            return terminals;
        }
        return Collections.EMPTY_LIST;
    }

    /**
     * 根据终端id 查询终端
     *
     * @param terminalId id
     * @return Terminal
     */
    public Terminal getCusTerminalById(Long terminalId) {
        String url = recordUrl + "terminal/"+ terminalId;
        Response response = restTemplate.getForObject(url, Response.class);
        if (response.getMeta().getCode() == Constants.RESPONSE_CODE_YES
                && response.getData() != null) {
            Map ter = (Map) response.getData();
            return BeanUtils.mapToBean(ter, Terminal.class);
        }
        return null;
    }

    /**
     * 查询电能表list
     *
     * @param params 查询参数
     *               page 页数
     *               rows 每页显示条数
     *               terminalId 集中器id
     *               customerId 用户ID
     * @return Response
     */
    @HystrixCommand(fallbackMethod = "fastFallbackWithMap")
    public Response getCusMeterPage(Map<String, Object> params) {
        if (StringUtils.isEmpty(params.get("terminalId")) || StringUtils.isEmpty(params.get("page"))
                || StringUtils.isEmpty(params.get("rows"))) {
            throw new MsgException("查询电能表失败,参数不全");
        }
        String url = recordUrl + "meters/"+ params.get("terminalId");
        params.remove("terminalId");
        url = setGetParam(url, params);
        return restTemplate.getForObject(url, Response.class, params);
    }

    /**
     * 查询电能表list
     *
     * @param terminalId 查询参数
     *                   ① 什么都不传 查询所有
     *                   ② customerId 用户id
     *                   ③ terminalName 终端名称
     * @return Response
     */
    @SuppressWarnings("unchecked")
    @HystrixCommand(fallbackMethod = "fastFallbackWithAss")
    public PageResponse<MeterInfoDto> getCusMeters(Long terminalId, Integer page, Integer rows) {
        String url = recordUrl + "meters/"+ terminalId + "?page={page}&rows={rows}";
        Response response = restTemplate.getForObject(url, Response.class, page, rows);
        if (response.getMeta().getCode() == Constants.RESPONSE_CODE_YES
                && response.getData() != null) {
            List<Map> list =  (List<Map>)response.getData();
            List<MeterInfoDto> meterInfoDtos = new ArrayList<>(list.size());
            list.forEach(map -> meterInfoDtos.add(BeanUtils.mapToBean(map, MeterInfoDto.class)));
            return new PageResponse<>((int) list.size(), meterInfoDtos);
        }
        return new PageResponse<>(0, Collections.EMPTY_LIST);
    }

    public List<Terminal> fastFallbackListTerminal() {
        return Collections.emptyList();
    }

    /**
     * 熔断失败方法 String
     *
     * @return Response
     */
    public PageResponse<MeterInfoDto> fastFallbackWithAss(Long terminalId, Integer page, Integer rows, Throwable throwable) {
        LOGGER.error(RESTE_RROR, throwable);
        return new PageResponse<>(0, Collections.EMPTY_LIST);
    }

    /**
     * 熔断失败方法 map参数
     *
     * @return Response
     */
    public Response fastFallbackWithMap(Map<String, Object> params, Throwable throwable) {
        LOGGER.error(RESTE_RROR, throwable);
        return new Response().failure(Constants.FEIGN_FALLBACK_DEFAULT_MSG + ", params=" + params.toString());
    }

}
